/*
 * Copyright (c) 2011 Metrum Research Group LLC. All Rights Reserved.
 *
 * You may use this software under the terms of GPL v3 (http://www.gnu.org/licenses/gpl.html).
 *
 * METRUM RESEARCH GROUP LLC MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. METRUM RESEARCH GROUP LLC SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package sumo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SpecificImageServlet extends HttpServlet {

        /**
         * Need a UID to extend HttpServlet
         */
        private static final long serialVersionUID = 1L;

        // To-do: use a hash here
        private static String[] imageTypes = SumoPropertyManager.getConfig()
                        .getStringArray("images.type");
        private static String[] mimeTypes = SumoPropertyManager.getConfig()
                        .getStringArray("images.mime");

        public void doGet(HttpServletRequest req, HttpServletResponse res)
                        throws ServletException, IOException {
                // authorize
		HttpSession theSession = req.getSession();
                //String username = (String)theSession.getAttribute("username");
                // security
		String filePath = req.getParameter("file");
                ExpressionEvaluator R = (ExpressionEvaluator) theSession.getAttribute("evaluator");
                String readable = R.evaluate("writeLines(as.character(file.access('"+ filePath +"',4)))",false);
                if(readable.equals("-1")){
                	PrintWriter pw = res.getWriter();
                        pw.write("Not readable ...");
                        pw.close();
                        return;
                }
                // deliver
                File imageFile = new File(filePath);
                if (imageFile.exists()) {
                        byte[] imageBytes = getRawBytes(imageFile);
                        res.setContentType(getMimeTypeForImage(imageFile
                                        .getName().toLowerCase()));

                        res.setHeader("Content-Disposition", "inline; filename="
                                        + imageFile.getName());
                        res.setStatus(HttpServletResponse.SC_OK);

                        res.setHeader("Cache-Control", "no-store"); // HTTP 1.1
                        res.setHeader("Pragma", "no-cache"); // HTTP 1.0
                        res.setDateHeader("Expires", 0); // prevents caching at the proxy

                        ServletOutputStream out = res.getOutputStream();
                        out.write(imageBytes);
                        out.flush();
                        out.close();
                } else {
                        res.setContentType("text/plain");
                        res.setHeader("Cache-Control", "no-cache");
                        PrintWriter pw = res.getWriter();
                        pw.write("No image...");
                        pw.close();
                }
        }

        private final static byte[] getRawBytes(File f) {

                try {
                        FileInputStream fin = new FileInputStream(f);
                        byte[] buffer = new byte[(int) f.length()];
                        fin.read(buffer);
                        fin.close();
                        return buffer;
                } catch (Exception err) {
                        err.printStackTrace();
                }
                return null;
        }

        private static String getMimeTypeForImage(String fileName) {
                String theMime = null;
                String ext = SumoUtils.getFileExtension(fileName).toLowerCase();

                // To-do: use a hash here
                if (ext != null && imageTypes != null) {
                        for (int i = 0; i < imageTypes.length; i++) {
                                String testExt = imageTypes[i].toLowerCase();
                                if (ext.equals(testExt)) {
                                        theMime = mimeTypes[i];
                                        break;
                                }
                        }
               }                                        

                return theMime;
        }
}

